<template>
  <div>
    <el-card>
      <!--卡片头部-->
      <div slot="header">
        <!--条件表单-->
        <el-form :inline="true" :model="selectForm">
          <el-form-item label="ID">
            <el-input placeholder="商品ID" v-model="selectForm.id"></el-input>
          </el-form-item>
          <el-form-item label="名称">
            <el-input placeholder="商品名称" v-model="selectForm.name"></el-input>
          </el-form-item>
          <el-form-item label="售卖状态">
            <el-select clearable v-model="selectForm.status" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getAllData">查询</el-button>
            <el-button type="info" @click="clear">清空</el-button>
            <el-button type="danger" @click="deleteBatch" :disabled="ids.length <= 0">批量删除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--卡片主体-->
      <div>
        <!--增加商品数据对话框-->
        <el-dialog :visible.sync="addDialogVisible" ref="addDialog" title="新增商品信息" width="30%">
          <el-form :rules="rules" ref="addForm" :model="addProduct" label-width="73px" size="medium">
            <el-form-item label="名称" prop="name">
              <el-input v-model="addProduct.name" style="width: 250px; margin-left: -40px;"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select clearable v-model="addProduct.upStatus" placeholder="请选择"
                         style="width: 250px; margin-left: -40px;">
                <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number :min="0" v-model="addProduct.price"
                               style="width: 250px; margin-left: -40px;"></el-input-number>
            </el-form-item>
            <el-form-item label="库存">
              <el-input-number :min="1" v-model="addProduct.stock"
                               style="width: 250px; margin-left: -40px;"></el-input-number>
            </el-form-item>
            <el-form-item label="积分">
              <el-input-number :min="0" v-model="addProduct.payPoint"
                               style="width: 250px; margin-left: -40px;"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button style="margin-left: -40px" type="primary" @click="add">提交</el-button>
              <el-button @click="closeAddDialog">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!--修改商品数据对话框-->
        <el-dialog :visible.sync="updateDialogVisible" ref="updateDialog" title="编辑商品信息" width="30%">
          <el-form :rules="rules" ref="updateForm" :model="updateProduct" label-width="73px" size="medium">
            <el-form-item label="ID">
              <el-input readonly v-model="updateProduct.id" style="width: 250px; margin-left: -40px;"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="updateProduct.name" style="width: 250px; margin-left: -40px;"></el-input>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number :min="0" v-model="updateProduct.price"
                               style="width: 250px; margin-left: -40px;"></el-input-number>
            </el-form-item>
            <el-form-item label="库存">
              <el-input-number :min="1" v-model="updateProduct.stock"
                               style="width: 250px; margin-left: -40px;"></el-input-number>
            </el-form-item>
            <el-form-item label="积分">
              <el-input-number :min="0" v-model="updateProduct.payPoint"
                               style="width: 250px; margin-left: -40px;"></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button style="margin-left: -40px" type="primary" @click="update">提交</el-button>
              <el-button @click="closeUpdateDialog">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <el-button type="primary" style="margin-bottom: 10px; float: right" @click="openAddDialog">+ 增加商品
        </el-button>

        <!--数据表格-->
        <el-table :data="tableData" border @selection-change="selectIds">
          <el-table-column type="selection">
          </el-table-column>
          <el-table-column prop="id" label="ID" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="name" label="名称" header-align="center" align="center">
          </el-table-column>
          <el-table-column label="售卖状态" header-align="center" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.upStatus" active-color="green" inactive-color="red" :active-value="1"
                         :inactive-value="0" @change="updateStatus(scope.row.id, scope.row.upStatus)">
              </el-switch>
              <span :class="{ 'text-green': scope.row.upStatus, 'text-red': !scope.row.upStatus }"
                    style="margin-left: 10px;">{{ scope.row.upStatus ? '上架' : '下架' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价格" header-align="center" align="center">
            <template slot-scope="scope">
              <span>¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="payPoint" label="积分" header-align="center" align="center">
          </el-table-column>
          <el-table-column prop="operate" label="操作" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="findById(scope.row.id)">修改</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button type="text" style="color: red" @click="deleteById(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <br>

        <!--Pagination 分页-->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                       :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total=parseInt(tableCount)>
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "ProductView.vue",

  data() {
    return {
      //表单校验规则
      rules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
      },
      //批量删除id数组
      ids: [],
      //下拉菜单选项
      options: [
        {
          value: 1,
          label: '上架'
        },
        {
          value: 0,
          label: '下架'
        }
      ],
      //控制新增对话框是否可见
      addDialogVisible: false,
      //控制修改对话框是否可见
      updateDialogVisible: false,
      //条件表单
      selectForm: {
        id: '',
        name: '',
        status: ''
      },
      //增加商品数据
      addProduct: {
        name: '',
        upStatus: '',
        price: '',
        stock: '',
        payPoint: ''
      },

      //修改商品数据
      updateProduct: {
        id: '',
        name: '',
        price: '',
        stock: '',
        payPoint: ''
      },
      //表格数据
      tableData: [],
      //表格总条数
      tableCount: '',
      //页码
      page: 1,
      //每页记录数
      pageSize: 5,
    }
  },

  methods: {
    //打开添加对话框
    openAddDialog() {
      this.addDialogVisible = true
    },

    //打开修改对话框
    openUpdateDialog() {
      this.updateDialogVisible = true
    },

    //关闭新增对话框
    closeAddDialog() {
      this.addDialogVisible = false
    },

    //关闭修改对话框
    closeUpdateDialog() {
      this.updateDialogVisible = false
    },

    //批量选择id
    selectIds(val) {
      //提取每一行数据的id并封装到数组中
      this.ids = val.map(row => row.id)
    },

    //当前页码
    handleCurrentChange(val) {
      this.page = val;
      this.getAllData();
    },

    //每页记录数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAllData();
    },

    //查询数据
    getAllData() {
      //发送请求
      request.get('/product/admin/list', {
        params: {
          id: this.selectForm.id,
          name: this.selectForm.name,
          status: this.selectForm.status,
          page: this.page,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.tableCount = res.data.data.total
          this.tableData = res.data.data.rows
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    //清空条件表单
    clear() {
      this.selectForm = {}
      this.getAllData()
    },

    //根据id查询数据
    findById(id) {
      //打开数据对话框
      this.openUpdateDialog()
      //发送请求
      request.get(`/product/admin/${id}`).then(res => {
        if (res.data.code === 200) {
          this.updateProduct = res.data.data
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    //编辑数据
    update() {
      //校验表单是否通过，通过则发送请求
      this.$refs['updateForm'].validate(valid => {
        if (valid) {
          //发送请求
          request.put('/product/admin', this.updateProduct).then(res => {
            if (res.data.code === 200) {
              this.closeUpdateDialog()
              this.getAllData()
              this.$message.success({message: '恭喜你，修改成功', type: "success"})
              this.updateProduct = {}
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      })
    },

    //根据id删除数据
    deleteById(id) {
      //是否删除
      this.$confirm("此操作将删除该数据，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //发送请求
        request.delete(`/product/admin/${id}`).then(res => {
          if (res.data.code === 200) {
            this.$message.success("恭喜你，删除成功")
            this.getAllData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除")
      })
    },

    //批量删除数据
    deleteBatch() {
      //是否删除
      this.$confirm("此操作将删除多行数据，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //发送请求
        request.delete('/product/admin', {
          data: this.ids
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success("恭喜你，删除成功")
            this.getAllData()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        //用户点击取消按钮
        this.$message.info("已取消删除")
      })
    },

    //新增商品
    add() {
      //校验表单是否通过，通过则发送请求
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          //发送请求
          request.post('/product/admin', this.addProduct).then(res => {
            if (res.data.code === 200) {
              this.closeAddDialog()
              this.getAllData()
              this.$message.success({message: '恭喜你，添加成功', type: "success"})
              this.addProduct = {}
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      })
    },

    //修改商品状态
    updateStatus(id, upStatus) {
      const newStatus = upStatus ? 1 : 0
      // 发送请求
      request.put('/product/admin/status', {
        id,
        upStatus: newStatus
      }).then(res => {
        if (res.data.code === 200) {
          // 找到当前行的索引
          const rowIndex = this.tableData.findIndex(item => item.id === id);

          if (rowIndex !== -1) {
            // 更新当前行的 upStatus 属性
            this.tableData[rowIndex].upStatus = upStatus;
          }
        }
      });
    },
  },
  created() {
    this.getAllData()
  },
}
</script>

<style>
@import "@/css/global.css";

.text-green {
  color: green;
}

.text-red {
  color: red;
}
</style>